/*
 * @Author: Xiaohan Ma
 * @Date: 2018-08-21 10:05:24
 * @Last Modified by: Xiaohan Ma
 * @Last Modified time: 2018-08-31 18:28:15
 */

const fs = require('fs');
const path = require('path');
const rename = think.promisify(fs.rename, fs);
const assert = require('assert');
const BasicController = require('../BasicController.js');

module.exports = class extends BasicController {
  constructor(ctx) {
    super(ctx);
    assert(think.isFunction(this.model), 'this.model must be a function');
    this.MODEL = this.ctx.state.ApiInfo.model;
    this.params = {
      model: this.MODEL,
      data: this.post()
    };
  }

  //  上传项目图片或文件
  async uploadfilesAction() {
    try {
      const params = this.params;
      const file = this.file();
      const fileKeys = Object.getOwnPropertyNames(file);

      if (think.isEmpty(fileKeys)) {
        return this.fail('上传失败,图片不能为空');
      }
      for (const i of fileKeys) {
        let files = [];
        // 单张图片接收到的file 参数为object，多图片为array，统一将其转化为array
        if (think.isObject(file[i])) {
          files.push(file[i]);
        } else if (think.isArray(file[i])) {
          files = [...file[i]];
        }

        for (const item of files) {
          const fileid = think.uuid('v4');
          let name = path.extname(item.name);
          // name = `${think.md5(item.name)}${name}`;
          name = `${fileid}${name}`;
          const filepath = path.join(think.ROOT_PATH, `runtime/upload/labIntroduction/${params.data.relation_id}/${name}`);
          think.mkdir(path.dirname(filepath));
          await rename(item.path, filepath);
          const filedata = {};
          filedata.id = fileid;
          filedata.file_path = filepath;
          filedata.relation_id = params.data.relation_id;
          await this.model(params.model).uploadfilesAction(filedata);
          // 上传单张图片
          return this.success({id: fileid}, '上传成功');
        }
      }
    } catch (error) {
      return this.fail(503, '上传失败', error);
    }
  };

  async downloadAction() {
    const {
      filepath
    } = this.post();
    return this.ctx.download(filepath);
  }

  async deleteFileAction() {
    const params = this.params;
    const filesInfo = await this.model(params.model).deleteFileAction(params.data);
    return this.success(filesInfo);
  }

  async getUploadFileByIdAction() {
    const params = this.params;
    params.data.id = this.ID;
    const fileInfo = await this.model(params.model).getUploadFileByIdAction(params.data);
    return this.success(fileInfo, '查询成功');
  }

  // 前台展示接口
  async getlistAction() {
    const params = this.params;
    const list = await this.model(params.model).getlistAction();
    const display = list.filter(element => {
      let richtext = element.richtext;
      if (think.isEmpty(richtext)) {
        richtext = '';
      } else {
        richtext = richtext.richtext.toString('utf-8');
      }
      element.richtext = richtext;
      return element.status === 1;
    });
    return this.success(display, '获取成功');
  }
};

/**
 * @api {POST} /lab_introduction/lab_introduction/uploadfiles /uploadfiles
 * @apiDescription 项目文件上传
 * @apiGroup lab_introduction
 * @apiParam {String} relation_id 实验室介绍id
 *
 *
 * @apiVersion 1.0.0
 * @apiErrorExample {json} 错误返回值:
 *{
 *   "code": 1001,
 *   "msg": {
 *      "relation_id": "relation_id can not be blank"
 *   }
 *}
 *{
 *   "code": 0,
 *  "msg": "上传失败,文件不能为空"
 *}
 * @apiSuccessExample {json} 正确返回值:
 *    {
 *   "code": 0,
 *     "msg": [
 *      {
 *           "id": "028b88a7-f144-49f2-8ec9-c4bd603b7b29",
 *          "file_path": "/home/mdalang/projects/mobile_internet_website_server/runtime/upload/projectImgInfo/undefined/20180729-161755.png",
 *          "relation_id": "dda33412-8e95-40f9-92f5-f01df8dd2d21"
 *      }
 *  ],
 *  "data": "上传成功"
 * }
 */

/**
 * @api {post} /lab_introduction/lab_introduction/download /download
 * @apiDescription 下载文件
 * @apiGroup lab_introduction
 * @apiParam {String} filepath 文件url
 *
 *
 * @apiVersion 1.0.0
 * @apiErrorExample {json} 错误返回值:
 * {
 *  "code": 1001,
 *  "msg": {
 *      "filepath": "filepath can not be blank"
 *  }
 * }
 * @apiSuccessExample {json} 正确返回值:
 * 文件
 */

/**
 * @api {delete} /lab_introduction/lab_introduction/deleteFile /deleteFile
 * @apiDescription 根据id删除实验室介绍文件
 * @apiGroup lab_introduction
 *
 * @apiParam {String} id 实验室介绍文件id
 *
 *
 * @apiParamExample {object} 请求参数格式:
 *  {
 * id: 'dda33412-8e95-40f9-92f5-f01df8dd2d21',
 * }
 *
 * @apiVersion 1.0.0
 * @apiErrorExample {json} 错误返回值:
 * {
 * "code": 1001,
 * "msg": {
 *      "id": "id can not be blank"
 *  }
 * }
 * @apiSuccessExample {json} 正确返回值:
 * {
 *  "code": 0,
 *  "msg": "删除成功",
 *  "data": 0
 * }
 */

/**
 * @api {get} /lab_introduction/lab_introduction/get /get
 * @apiDescription 根据id查询单个实验室介绍信息
 * @apiGroup lab_introduction
 * @apiParam {String} id  实验室介绍id
 *
 *
 * @apiParamExample {string} 请求参数格式:
 *    ?id=8b3a12bd-6195-403b-9fcc-a6a053d6d073
 *
 * @apiVersion 1.0.0
 * @apiErrorExample {json} 错误返回值:
 *{
 *   "code": 1001,
 *   "msg": {
 *      "id": "id can not be blank"
 *   }
 *}
 * @apiSuccessExample {json} 正确返回值:
 * {
 *  "code": 0,
 *  "msg": "",
 *  "data": {
                "id": "18d92789-0240-4878-9b94-41078f2dbd50",
                "title": "实验室介绍",
                "richtext": "你说啊这个项目是什么名字",
                introduction_files: [],
                "create_time": "2018-08-09",
                "update_time": "2018-08-10"，
                 "status":0
 *  }
 * }
 */

/**
 * @api {delete} /lab_introduction/lab_introduction/del /del
 * @apiDescription 根据id删除项目
 * @apiGroup lab_introduction
 *
 * @apiParam {String} id  实验室介绍id
 *
 *
 * @apiParamExample {object} 请求参数格式:
 *  {
 * id: dda33412-8e95-40f9-92f5-f01df8dd2d21,
 * }
 *
 * @apiVersion 1.0.0
 * @apiErrorExample {json} 错误返回值:
 * {
 * "code": 1001,
 * "msg": {
 *      "id": "id can not be blank"
 *  }
 * }
 * @apiSuccessExample {json} 正确返回值:
{
    "code": 0,
    "msg": "",
    "data": {
        "projectInfoData": 1,
        "richTextData": 1,
        "projectfiles": 3
    }
}
 */

/**
 * @api {post} /lab_introduction/lab_introduction/edit /edit
 * @apiDescription 根据id查询修改项目信息
 * @apiGroup lab_introduction
 *
 * @apiParam {String} id 实验室介绍ID
 * @apiParam {String} [title] 实验室介绍title
 * @apiParam {String} [richtext] 实验室介绍内容
 * @apiParam {Number} [status] 状态

 *
 * @apiParamExample {object} 请求参数格式:
 *  {
 *  id: '18d92789-0240-4878-9b94-41078f2dbd50',
 *  title: '实验室介绍',
 *  richtext: '<p>你说啊这个项目是什么名字</p>',
 * }
 *
 * @apiVersion 1.0.0
 * @apiErrorExample {json} 错误返回值:
 * {
 * "code": 1001,
 * "msg": {
 *      "id": "id can not be blank"
 *  }
 * }
 * @apiSuccessExample {json} 正确返回值:
 *{
 *   "errno": 0,
 *   "errmsg": "",
 *   "data": 1
*}
*/

/**
 * @api {POST} /lab_introduction/lab_introduction/listall /listall
 * @apiDescription 获取全部实验室介绍列表/根据条件获取实验室介绍列表
 * @apiGroup lab_introduction
 *
 * @apiParam {String} [id] 实验室介绍ID
 * @apiParam {String} [title] 实验室介绍title
 * @apiParam {String} [richtext] 实验室介绍内容
 * @apiParam {array} [introduction_files] 实验室介绍文件/图片
 * @apiParam {String} [create_time]  实验室介绍创建时间
 * @apiParam {String} [update_time] 实验室介绍更新时间
 * @apiParam {Number} [status] 状态
 *
 * @apiVersion 1.0.0
 * @apiErrorExample {json} 错误返回值:
 *     {
 *        "code": ,
 *        "msg": "获取失败",
 *        "error": {
 *        },
 *     }
 *
 * @apiSuccessExample {json} 正确返回值:
 * {
 *  "code": 0,
 *  "msg": "",
 *  "data": [
 *      {
           "id": "18d92789-0240-4878-9b94-41078f2dbd50",
           "title": "实验室介绍",
           "richtext": "你说啊这个项目是什么名字",
           'introduction_files': [],
           "create_time": "2018-08-09",
           "update_time": "2018-08-10"，
           "status":0
 *      }
 *  ]
 * }
 */

/**
 * @api {POST} /lab_introduction/lab_introduction/listpage /listpage
 * @apiDescription 获取全部项目列表/根据条件分页获取实验室介绍列表
 * @apiGroup lab_introduction
 *
 * @apiParam {String} [id] 实验室介绍ID
 * @apiParam {String} [title] 实验室介绍title
 * @apiParam {String} [richtext] 实验室介绍内容
 * @apiParam {array} [introduction_files] 实验室介绍文件/图片
 * @apiParam {String} [create_time]  实验室介绍创建时间
 * @apiParam {String} [update_time] 实验室介绍更新时间
 * @apiParam {Number} [status] 状态
 * @apiParam {Number} [page] 页数
 * @apiParam {Number} [pageSize] 数据条数
 *
 *
 *  * @apiParamExample {get} Request-Example:
                 {
                   page:1,
                   pageSize:10,
                   create_time:2018-08-09
                  }
 * @apiVersion 1.0.0
 * @apiErrorExample {json} 错误返回值:
 *     {
 *        "code": ,
 *        "msg": "获取失败",
 *        "error": {
 *        },
 *     }
 *
 * @apiSuccessExample {json} 正确返回值:
{
    "code": 0,
    "msg": "",
    "data": {
        "pageSize": 10,
        "current": 1,
        "pages": 1,
        "total": 2,
        "data": [
            {
                "id": "18d92789-0240-4878-9b94-41078f2dbd50",
                "title": "实验室介绍",
                "richtext": "你说啊这个项目是什么名字",
                "introduction_files": [],
                "create_time": "2018-08-09",
                "update_time": "2018-08-10"，
                "status":0
            }
        ]
    }
}
 */

/**
 * @api {POST} /lab_introduction/lab_introduction/add /add
 * @apiDescription 新增实验室介绍
 * @apiGroup lab_introduction
 *
 * @apiParam {String} title 实验室介绍名称
 * @apiParam {Number} [status] 状态
 *
 * @apiVersion 1.0.0
 * @apiErrorExample {json} 错误返回值:
 * {
 * "code": 1001,
 * "msg": {
 *      "title": "title can not be blank"
 *  }
 * }
 *
 * @apiSuccessExample {json} 正确返回值:
 * {
 *  "code": 0,
 *  "msg": "",
 *  "data": {
 *      "id": "ea6ccba8-f47d-4a0c-b54b-eef565f56829"
 *  }
 * }
 */

/**
 * @api {POST} /lab_introduction/lab_introduction/getlist /getlist 前台接口
 * @apiDescription 获取全部项目列表
 * @apiGroup lab_introduction
 *
 * @apiParam {String} [id] 实验室介绍ID
 * @apiParam {String} [title] 实验室介绍title
 * @apiParam {String} [richtext] 实验室介绍内容
 * @apiParam {array}  [introduction_files] 实验室介绍文件/图片
 * @apiParam {String} [create_time]  实验室介绍创建时间
 * @apiParam {String} [update_time] 实验室介绍更新时间
 * @apiParam {Number} [status] 状态
 *
 *
 * @apiParamExample {get} Request-Example:
    { }
 * @apiVersion 1.0.0
 * @apiErrorExample {json} 错误返回值:
 *     {
 *        "code": ,
 *        "msg": "获取失败",
 *        "error": {
 *        },
 *     }
 *
 * @apiSuccessExample {json} 正确返回值:
{
    "code": 0,
    "msg": "获取成功",
    "data": [
        {
            "id": "00d9b541-17d2-467e-bfdd-f45e8e901edf",
            "title": "567",
            "status": 1,
            "create_time": "2018-08-22 16:46:04",
            "update_time": "2018-08-27 10:55:54",
            "introduction_files": [],
            "richtext": ""
        }
    ]
}
 */
